<template>
  <el-dialog :visible="visible" :append-to-body="true" width="390px" @close="$emit('update:visible', false)"
    class="c-LotteryConfig">
    <div class="c-LotteryConfigtitle" slot="title">
      <span :style="{ fontSize: '16px', marginRight: '20px' }">
        抽奖配置
      </span>
      <el-button size="mini" @click="addLottery">增加奖项</el-button>
      <el-button size="mini" type="primary" @click="onSubmit">保存配置</el-button>
      <el-button size="mini" @click="$emit('update:visible', false)">取消</el-button>
    </div>
    <div class="container">
      <el-form ref="form" :model="form" size="mini">
        <el-form-item label="抽奖标题">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="抽奖总人数">
          <el-input type="number" v-model="form.number" :min="1" :step="1"></el-input>
        </el-form-item>
        <el-form-item label="一等奖">
          <el-input type="number" v-model="form.firstPrize" :min="0" :step="1"></el-input>

          <el-input type="text" placeholder="奖品说明" v-model="pptext_.firstPrize"
            @change="handleChange_text($event, 'firstPrize')" show-word-limit> </el-input>
          <el-button style="width: 100%;" type="primary">上传奖品图片</el-button>
          <input type="file" @change="handleChange_photo($event, 'firstPrize')" style="width: 100%;height: 28px; position: absolute; left: 0%; opacity: 0;">

        </el-form-item>
        <el-form-item :label="newitem.name" v-for="newitem in storeNewLottery" :key="newitem.key">
          <el-input type="number" :min="0" :step="1" v-model="form[newitem.key]" @change="
              val => {
                form[newitem.key] = Number(val);
              }
            "></el-input>

          <el-input type="text" placeholder="奖品说明" v-model="pptext_[newitem.key]"
            @change="handleChange_text($event, newitem.key)" show-word-limit> </el-input>
          <el-button style="width: 100%;" type="primary">上传奖品图片</el-button>
          <input type="file" @change="handleChange_photo($event, newitem.key)" style="width: 100%;height: 28px; position: absolute; left: 0%; opacity: 0;">

        </el-form-item>
      </el-form>
    </div>

    <el-dialog :visible.sync="showAddLottery" :append-to-body="true" width="300px" class="dialog-showAddLottery">
      <div class="add-title" slot="title">增加奖项</div>
      <el-form ref="newLottery" :model="newLottery" size="mini">
        <el-form-item label="奖项名称">
          <el-input v-model="newLottery.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHandler">增加奖项</el-button>
          <el-button @click="showAddLottery = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-dialog>
</template>
<script>
  import {
    setData,
    getData,
    configField
  } from '@/helper/index';
  import {
    randomNum
  } from '@/helper/algorithm';
  export default {
    name: 'LotteryConfig',
    props: {
      visible: Boolean
    },
    computed: {
      form: {
        get() {
          return this.$store.state.config;
        },
        set(val) {
          // this.$store.commit('setConfig', val);
          return val;
        }
      },
      storeNewLottery() {
        console.log('storeNewLottery', this.$store.state.newLottery)
        return this.$store.state.newLottery;
      }
    },
    created() {
      // var data = getData("photo_");
      // if (data && data.length !== 0) {
      //   let item_ = 0;
      //   for (; item_ < data.length; item_++) {
      //     this.$set(this.pptext_,data[item_].id,data[item_].text)
      //     // this.pptext_[data[item_].id] = "" + data[item_].text
      //   }
      // }
    },
    data() {
      return {
        showAddLottery: false,
        newLottery: {
          name: ''
        },
        ppfile: null,
        pptext_: {
          firstPrize: ''
        }
      };
    },
    methods: {
      onSubmit() {
        setData(configField, this.form);
        this.$store.commit('setConfig', this.form);
        this.$emit('update:visible', false);

        this.$message({
          message: '保存成功',
          type: 'success'
        });

        this.$nextTick(() => {
          this.$emit('resetconfig');
        });
      },
      addLottery() {
        this.showAddLottery = true;
      },
      randomField() {
        const str = 'abcdefghijklmnopqrstuvwxyz';
        let fieldStr = '';
        for (let index = 0; index < 10; index++) {
          fieldStr += str.split('')[randomNum(1, 27) - 1];
        }
        return `${fieldStr}${Date.now()}`;
      },
      addHandler() {
        const field = this.randomField();
        const data = {
          key: field,
          name: this.newLottery.name
        };
        this.$store.commit('setNewLottery', data);

        this.showAddLottery = false;

        var data_ = getData("photo_")
        if (data_ && data_.length != 0) {
          data_.push({
            id: field,
            text: '',
            url: '',
            name: this.newLottery.name
          })
          setData("photo_", data_)
        } else {
          setData("photo_", [{
            id: field,
            text: '',
            url: '',
            name: this.newLottery.name
          }])
        }
      },
      handleChange_photo(event, value) {
        console.log('event', event, value)
        var fileList = event.target.files;
        console.log('file', fileList)
        const formData = new FormData();
        formData.append('uploadImg_', fileList);
        const reader = new FileReader();
        const file = fileList[0];
        var data = getData("photo_");
        if (file) {
          console.log('file', file, reader)
          reader.readAsDataURL(file);
          reader.onload = () => {
            if (data && data.length !== 0) {
              for (let index = 0; index < data.length; index++) {
                if (data[index].id === value) {
                  data[index].url = reader.result
                  setData("photo_", data)
                  return;
                }
              }
              data.push({
                id: value,
                text: '',
                url: reader.result
              })
            } else {
              data = [{
                id: value,
                text: '',
                url: reader.result
              }]
            }
            setData("photo_", data)
          }
        } else {
          for (let index = 0; index < data.length; index++) {
            if (data[index].id === value) {
              data[index].url = ''
              setData("photo_", data)
              return;
            }
          }
        }
      },
      handleChange_text(event, value) {
        console.log('event!!', event, value)
        var data = getData("photo_");
        var text = event
        if (data && data.length !== 0) {
          let index_ = 0
          for (; index_ < data.length; index_++) {
            if (data[index_].id === value) {
              data[index_].text = text
              setData("photo_", data)
              return;
            }
          }
          data.push({
            id: value,
            text: text,
            url: ''
          })
        } else {
          data = [{
            id: value,
            text: text,
            url: ''
          }]
        }
        setData("photo_", data)
      }
    }
  };
</script>
<style lang="scss">
  .el-upload.el-upload--text,
  .ppclas {
    width: 100%;
    margin-top: 3px;
  }

  .c-LotteryConfig {
    .el-dialog__body {
      height: 340px;

      .container {
        height: 100%;
        overflow-y: auto;
        padding: 0 10px;
      }
    }
  }

  .dialog-showAddLottery {
    .el-dialog {
      height: 186px;
    }
  }
</style>